import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Permission, PermissionDocument } from './schemas/permission.schema';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { RolesService } from '../roles/roles.service';

@Injectable()
export class PermissionsService {
  constructor(
    @InjectModel(Permission.name) private permissionModel: Model<PermissionDocument>,
    private rolesService: RolesService,
  ) {}
  
  async create(createPermissionDto: CreatePermissionDto): Promise<Permission> {
    // 检查权限代码是否已存在
    const existingPermission = await this.permissionModel.findOne({ 
      code: createPermissionDto.code 
    }).exec();
    
    if (existingPermission) {
      throw new BadRequestException('权限代码已存在');
    }
    
    const createdPermission = new this.permissionModel(createPermissionDto);
    return createdPermission.save();
  }
  
  async findAll(): Promise<Permission[]> {
    return this.permissionModel.find().exec();
  }
  
  async findOne(id: string): Promise<Permission> {
    const permission = await this.permissionModel.findById(id).exec();
    
    if (!permission) {
      throw new NotFoundException(`权限 ID ${id} 不存在`);
    }
    
    return permission;
  }
  
  async update(id: string, updatePermissionDto: UpdatePermissionDto): Promise<Permission> {
    // 如果更新了code，检查是否已存在
    if (updatePermissionDto.code) {
      const existingPermission = await this.permissionModel.findOne({
        code: updatePermissionDto.code,
        _id: { $ne: id }
      }).exec();
      
      if (existingPermission) {
        throw new BadRequestException('权限代码已存在');
      }
    }
    
    const updatedPermission = await this.permissionModel.findByIdAndUpdate(
      id, 
      updatePermissionDto, 
      { new: true }
    ).exec();
    
    if (!updatedPermission) {
      throw new NotFoundException(`权限 ID ${id} 不存在`);
    }
    
    return updatedPermission;
  }
  
  async remove(id: string): Promise<void> {
    const permission = await this.permissionModel.findById(id).exec();
    
    if (!permission) {
      throw new NotFoundException(`权限 ID ${id} 不存在`);
    }
    
    // 从所有角色中移除此权限引用
    await this.removePermissionFromRoles(id);
    
    await this.permissionModel.findByIdAndDelete(id).exec();
  }
  
  // 批量删除权限
  async removeMany(ids: string[]): Promise<void> {
    // 从所有角色中移除这些权限引用
    for (const id of ids) {
      await this.removePermissionFromRoles(id);
    }
    
    await this.permissionModel.deleteMany({ _id: { $in: ids } }).exec();
  }
  
  // 根据代码查找权限
  async findByCode(code: string): Promise<Permission | null> {
    return this.permissionModel.findOne({ code }).exec();
  }
  
  // 从所有角色中移除权限引用的辅助方法
  private async removePermissionFromRoles(permissionId: string): Promise<void> {
    // 注意：此方法需要在RolesService中实现
    // 可以通过注入RolesService到PermissionsService来实现
    await this.rolesService.removePermissionFromRoles(permissionId);
  }
} 